import turbogears   as tg

import logging
import cherrypy
import sqlobject
from sqlalchemy.exceptions import SQLError
from kaizen.model import Action, Tag, Project, Context,session
from turbogears import identity, expose, validate, validators, redirect, error_handler, flash, widgets, view
from formencode import validators

log = logging.getLogger("kaizen.subcontrollers.tag")

class TagController:


    @expose(template="kaizen.templates.createTag", content_type='text/html; charset=utf-8')
    @validate(validators={"title" : validators.NotEmpty()})
    @error_handler()
    def create(self, title, tg_errors=None, **keywords):
        #if no title given
        if tg_errors:
            log.debug("no title")
            tg.flash("You must enter a title")
            return dict()
        try:
          log.debug("new tag")
          tag = Tag(title=title)
          tag.flush()
        #todo add code completion
        except SQLError,x:
           log.error("error", x)
           tg.flash("Tag already exists")
           contexts = model.Context.select()
           return dict(contexts=contexts)
        tg.flash("Tag added")
        return dict()

